package com.legna.mhxy.support.service;

import com.legna.mhxy.support.dao.RingCategoryDao;
import com.legna.mhxy.support.dao.RingTaskLogDao;
import com.legna.mhxy.support.dao.RingTypeDao;
import com.legna.mhxy.support.dao.UserRingDao;
import com.legna.mhxy.support.entity.RingTaskLog;
import com.legna.mhxy.support.entity.UserRing;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
@Slf4j
public class StockService {
    private final RingCategoryDao ringCategoryDao;
    private final RingTypeDao ringTypeDao;
    private final UserRingDao userRingDao;
    private final RingTaskLogDao ringTaskLogDao;

    public void increase(Long userRingId,Integer count){
        UserRing userRing = userRingDao.selectById(userRingId);
        userRing.setRingCount(userRing.getRingCount() + count);
        userRingDao.updateById(userRing);
    }
    public void decrease(Long userRingId,Integer count,Long taskId){
        RingTaskLog log = null;
        UserRing userRing = userRingDao.selectById(userRingId);
        if (userRing.getRingCount() > 0 && userRing.getRingCount() >= count){
            userRing.setRingCount(userRing.getRingCount() - count);
            userRingDao.updateById(userRing);
            log = new RingTaskLog(taskId,userRing.getId(),1);
        }else{
            log = new RingTaskLog(taskId,userRing.getId(),2);
        }
        ringTaskLogDao.insert(log);
    }

    public void increaseByUserType(Long userId, Long typeId, Integer count) {
        UserRing userRing = userRingDao.selectUserRing(typeId, userId);
        userRing.setRingCount(userRing.getRingCount() - count);
        userRingDao.updateById(userRing);
    }
    public void decreaseByUserType(Long userId, Long typeId, Integer count,Long taskId) {
        RingTaskLog log = null;
        UserRing userRing = userRingDao.selectUserRing(typeId, userId);
        if (userRing.getRingCount() > 0 && userRing.getRingCount() >= count){
            userRing.setRingCount(userRing.getRingCount() - count);
            userRingDao.updateById(userRing);
            log = new RingTaskLog(taskId,userRing.getId(),1);
        }else{
            log = new RingTaskLog(taskId,userRing.getId(),2);
        }

        ringTaskLogDao.insert(log);
    }
}
